import {
    reqAddArticleFromWangEditor,
    reqDeleteArticleByWangEditor,
    reqGetArticle,
    reqGetArticleByPage,
    reqGetArticleCount,
    reqGetArticleId
} from "@/api/article";
import {requestGetData, requestIsSuccess} from "@/api/request";

export class Article {
    constructor({id,article,file,createtime,intro,title,userinfoid}) {
        this.id=id;
        this.article=article;
        this.file=file;
        this.createtime=createtime;
        this.intro=intro;
        this.title=title;
        this.userinfoid=userinfoid;
    }

    /**
     * 删除文章对象，成功返回true
     * @returns {Promise<boolean>}
     */
    async deleteArticle() {
        let result = await reqDeleteArticleByWangEditor(this.id)
        if(requestIsSuccess(result)){
            return true
        }else{
            return false
        }
    }

    /**
     * 更新article，成功返回true
     * @returns {Promise<void>}
     */
    async updateArticle(){
        const result = await reqAddArticleFromWangEditor(this);
        if(requestIsSuccess(result)) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获得文章个数，失败返回 undefined
     * @returns {Promise<number|*>}
     */
    static async getArticleCount(){
        const result = await reqGetArticleCount();
        if(requestIsSuccess(result)){
            return requestGetData(result)
        }else{
            return void 0;
        }
    }

    /**
     * 分页获取文章列表
     * @param currentPage 当前页
     * @param pageSize 每页个数
     * @returns {Promise<[]|*[]>}
     */
     static async getArticleByPage(currentPage, pageSize) {
         const result = await reqGetArticleByPage(currentPage, pageSize);
         if (requestIsSuccess(result)) {
             let articleList = []
             requestGetData(result).forEach(tArticle => {
                 articleList.push(new Article(tArticle))
             })
             return articleList
         } else {
             return [];
         }
     }

    /**
     * 通过Id获取Article
     * @param id
     * @returns {Promise<*|Article>}
     */
     static async getArticleById(id){
         const result = await reqGetArticle(id);
         if (requestIsSuccess(result)) {
             return new Article(requestGetData(result));
         } else {
             return void 0
         }
     }

    /**
     * 在服务端创建一个文章对象
     * @returns {Promise<*|Article>}
     */
     static async createArticle(){
         const result = await reqGetArticleId();
         if(requestIsSuccess(result)){
             return new Article({id:requestGetData(result)})
         }else{
             return void 0
         }
     }
}